package com.sunyur.tailor.channel.service.inner.sendorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.collect.Lists;
import com.sunyur.tailor.channel.common.inner.base.SunyurListResult;
import com.sunyur.tailor.channel.common.inner.base.SunyurResult;
import com.sunyur.tailor.channel.common.inner.util.SunyurClientUtil;
import com.sunyur.tailor.channel.common.inner.util.SunyurResultUtil;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelListResultUtil;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.receiveorder.model.CreateReceiveOrderModel;
import com.sunyur.tailor.channel.service.inner.sendorder.model.SunyurSendOrderHeadModel;
import com.sunyur.tailor.channel.service.inner.sendorder.model.SunyurSendOrderItemModel;
import com.sunyur.tailor.channel.service.inner.sendorder.param.*;
import com.sunyur.tailor.channel.service.inner.sendorder.service.SunyurSendOrderService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName SendOrderServiceImpl
 * @Description 商城发货单服务
 * @Author yu.chen
 * @Date 2021/4/29 4:18
 * @Version 1.0
 **/
@Service("sunyurSendOrderService")
public class SunyurSendOrderServiceImpl implements SunyurSendOrderService {

    private static final Logger LOGGER_INFO = LoggerFactory.getLogger(SunyurSendOrderServiceImpl.class);
    private static final Logger LOGGER_ERROR = LoggerFactory.getLogger(SunyurSendOrderServiceImpl.class);

    /**
     * 请求商越Client
     */
    @Autowired
    private SunyurClientUtil sunyurClient;

    /**
     * 发货单取消 链接
     */
    @Value("${sunyur.api.cancelSendOrder}")
    private String cancelSendOrder;


    /**
     * 获取发货单头 链接
     */
    @Value("${sunyur.api.getSendOrderHeadInfo}")
    private String getSendOrderHeadInfo;

    /**
     * 获取发货单行 链接
     */
    @Value("${sunyur.api.getSendOrderListItem}")
    private String getSendOrderListItem;

    /**
     * @description 发货单取消
     * @param sendOrderCancelParam
     * @return com.sunyur.tailor.channel.common.middle.base.ChannelResult
     * @author yu.chen
     * @date 2021/4/29 4:22
     * @Version v1.0
     */
    @Override
    public ChannelResult cancelSendOrder(SendOrderCancelParam sendOrderCancelParam) throws Exception {
        LOGGER_INFO.info("SunyurSendOrderServiceImpl cancelSendOrder param is {}", JSON.toJSONString(sendOrderCancelParam));
        if (ObjectUtils.isEmpty(sendOrderCancelParam)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurSendOrderServiceImpl cancelSendOrder param is null");
        }
        // 调用主线接口
        SunyurResult sunyurResult = sunyurClient.execPost(cancelSendOrder, JSON.toJSONString(sendOrderCancelParam), new TypeReference<SunyurResult<CreateReceiveOrderModel>>() {});
        // 主线报错
        if (!SunyurResultUtil.isSuccess(sunyurResult)) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        return ChannelResultUtil.success(null);
    }

    @Override
    public ChannelResult<SunyurSendOrderHeadModel> getSendOrderHeadInfo(SunyurSendOrderHeadParam sendOrderHeadReq) throws Exception {
        LOGGER_INFO.info("SunyurOrderServiceImpl getSendOrderHeadInfo param is {}", JSON.toJSONString(sendOrderHeadReq));
        if (ObjectUtils.isEmpty(sendOrderHeadReq)) {
            return ChannelResultUtil.error(MiddleResultEnum.PARAM_NULL.getCode(), "SunyurOrderServiceImpl getSendOrderHeadInfo param is null");
        }
        // 调用主线接口
        SunyurResult<SunyurSendOrderHeadModel> sunyurResult = sunyurClient.execPost(getSendOrderHeadInfo, JSON.toJSONString(sendOrderHeadReq), new TypeReference<SunyurResult<SunyurSendOrderHeadModel>>() {
        });
        // 主线报错
        if (!"success".equals(sunyurResult.getCode())) {
            return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        return ChannelResultUtil.success(sunyurResult.getContent());
    }

    @Override
    public ChannelResult<List<SunyurSendOrderItemModel>> getSendOrderListItem(SunyurSendOrderItemParam sendOrderItemReq) throws Exception {
        LOGGER_INFO.info("SunyurOrderServiceImpl getSendOrderListItem param is {}", JSON.toJSONString(sendOrderItemReq));
        if (ObjectUtils.isEmpty(sendOrderItemReq) || StringUtils.isBlank(sendOrderItemReq.getSendOrderCode())) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), "SunyurOrderServiceImpl getSendOrderListItem param is null");
        }
        // 设置为每页最大条数
        sendOrderItemReq.setPageSize(100);
        // 调用主线查询采购单头信息接口
        TypeReference<SunyurListResult<SunyurSendOrderItemModel>> typeReference = new TypeReference<SunyurListResult<SunyurSendOrderItemModel>>() {
        };
        SunyurListResult<SunyurSendOrderItemModel> sunyurResult = sunyurClient.execListPost(getSendOrderListItem, JSON.toJSONString(sendOrderItemReq), typeReference);
        // 主线返回错误
        if (!"success".equals(sunyurResult.getCode())) {
            return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurResult.getErrorMessage());
        }
        // 判断是否存在下一页
        if (!SunyurResultUtil.isNextPage(sunyurResult)) {
            return ChannelListResultUtil.success(sunyurResult.getContent());
        }

        // 返回结果集
        List<SunyurSendOrderItemModel> sendOrderItemModelList = Lists.newArrayList();
        // 将第一次查询的结果收集
        sendOrderItemModelList.addAll(sunyurResult.getContent());
        // 循环查询剩余数据
        for (int i = sendOrderItemReq.getPage() + 1; i <= sunyurResult.getTotalPage(); i++) {
            sendOrderItemReq.setPage(i);
            // 调用主线查询采购单头信息接口
            SunyurListResult<SunyurSendOrderItemModel> sunyurPageResult = sunyurClient.execListPost(getSendOrderListItem, JSON.toJSONString(sendOrderItemReq), typeReference);
            // 某次调用主线返回错误（小概率，可能网络等原因，此时结果集数据不完整，本次查询失败）
            if (!"success".equals(sunyurPageResult.getCode())) {
                LOGGER_ERROR.error("getSendOrderListItem  loop call sunyur request fail, param is {}, result is {}", JSON.toJSONString(sendOrderItemReq), JSON.toJSONString(sunyurPageResult));
                return ChannelListResultUtil.error(MiddleResultEnum.FAILED.getCode(), sunyurPageResult.getErrorMessage());
            }
            sendOrderItemModelList.addAll(sunyurPageResult.getContent());
        }
        return ChannelListResultUtil.success(sendOrderItemModelList);
    }
}
